package com.miyake.client;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;

public class GoogleLoginComposite extends Composite {
	interface LoginHandler {
		void onLogin(boolean login);
	};
	List<LoginHandler> handlers = new ArrayList<LoginHandler>();
	public void addLoginHandler(LoginHandler handler) {
		handlers.add(handler);
	}
	protected void fireOnLogin(boolean login) {
		for (LoginHandler handler : handlers) {
			handler.onLogin(login);
		}
	}
	
	private LoginInfo loginInfo = null;
	private HorizontalPanel loginPanel = new HorizontalPanel();
	private HorizontalPanel mainPanel = new HorizontalPanel();
	private Anchor signInLink = new Anchor("Sign in");
	private Anchor signOutLink = new Anchor("Sign out");
 
	protected void loadLogin() {
	    signInLink.setHref(loginInfo.getLoginUrl());
	    loginPanel.add(signInLink);
	    verticalPanel.add(loginPanel);
	}
  
	protected void loadMain() {
		mainPanel.add(new HTML("<b>"+ loginInfo.getEmail()+"</b>"));
		mainPanel.add(new Label(" | "));
		mainPanel.add(signOutLink);
		signOutLink.setHref(loginInfo.getLogoutUrl());
		verticalPanel.add(mainPanel);
  }

	HorizontalPanel verticalPanel;
	public GoogleLoginComposite() {
		verticalPanel = new HorizontalPanel();
		initWidget(verticalPanel);
		DoctorsUserServiceAsync loginService = DoctorsUserService.Util.getInstance();
		    loginService.login(GWT.getHostPageBaseURL(),
    		new AsyncCallback<LoginInfo>(){
    			public void onFailure(Throwable error){
    			}
        
    			public void onSuccess(LoginInfo result){
    				loginInfo = result;
    				if(loginInfo.isLoggedIn()){
    					loadMain();
    					fireOnLogin(true);
    				}
    				else{
    					//loadLogin();
    					Window.Location.assign(result.getLoginUrl());
    					//loginInfo.getLoginUrl();
    				}
    			}
    		});
	
	
	}

}
